package com.flyqiu.flow.core.manage;

import com.alibaba.fastjson2.JSONObject;
import com.flyqiu.flow.api.format.FlyQiuFlowBpmnFormatManage;
import com.flyqiu.flow.api.format.IBpmnFormat;
import com.flyqiu.common.tools.StringTools;

import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class DefaultFlyQiuFlowBpmnFormatManage implements FlyQiuFlowBpmnFormatManage {
    private final Map<String, IBpmnFormat> bpmnFormatMap;

    public DefaultFlyQiuFlowBpmnFormatManage() {
        bpmnFormatMap = new HashMap<>();
    }

    @Override
    public void registerBpmnFormat(IBpmnFormat bpmnFormat) {
        if (StringTools.isBlank(bpmnFormat.formatType())) {
            throw new RuntimeException("No format type specified");
        }
        List<String> types = Arrays.stream(bpmnFormat.formatType().split(",")).filter(e -> !StringTools.isBlank(e)).toList();
        if (types.isEmpty()) {
            throw new RuntimeException("No format type specified");
        }
        for (String type : types) {
            bpmnFormatMap.put(type, bpmnFormat);
        }

    }

    @Override
    public JSONObject convertStartBpmn(String data, String currentFormatType) {
        return getBpmnFormatMap(currentFormatType).convertStartBpmn(data);
    }

    @Override
    public JSONObject convertStartBpmn(byte[] bytes, String currentFormatType) {
        return getBpmnFormatMap(currentFormatType).convertStartBpmn(bytes);
    }

    @Override
    public byte[] convertTargetFormatByte(byte[] jsonStrData, String targetFormatType) {
        return getBpmnFormatMap(targetFormatType).convertTargetFormatByte(jsonStrData);
    }


    public IBpmnFormat getBpmnFormatMap(String type) {
        if (!bpmnFormatMap.containsKey(type)) {
            throw new RuntimeException("No formatter found for the specified type:" + type);
        }
        return bpmnFormatMap.get(type);
    }
}
